<!DOCTYPE html>
<html lang="zh_CN">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<div id="w1">
		<p id="demo"></p>
		<div></div>
	</div>
	<div id="w2"></div>


	<script type="text/javascript">
		// 7:丰富元素获取
		// selector 选择器,context 上下文
		var A = function(selector, context) {
			return new A.fn.init(selector, context);
		}
		A.fn = A.prototype = {
			init: function(selector, context) {
				// 获取元素长度
				this.length = 0;
				// 默认获取上下文为 document
				context = context || document;
				// 如果是 id 选择器,0 按位取反转为 -1,非0即为true
				if (~selector.indexOf('#')) {
					// 截取 id 并选择
					this[0] = document.getElementById(selector.slice(1));
					this.length = 1;
				// 如果是元素名称
				} else {
					var doms = context.getElementsByTagName(selector),
						i = 0,
						len = doms.length;
					for (; i < len; i++) {
						this[i] = doms[i];
					}
					this.length = len;
				}
				// 保存上下文
				this.context = context;
				// 保存选择器
				this.selector = selector;
				// 返回对象
				return this;
			}
		};

		console.log(A('#demo'));
		console.log(A('div'));

		console.log( A('p', document.getElementById('w2')) );
	</script>
</body>
</html>